<?php
namespace app\food\controller;

use app\food\model\Category;
use app\food\model\Comment;
use app\food\model\Product;
use think\Config;
use think\Request;
use think\Controller;
use think\Session;

class Index extends Controller
{
    /**主页
     * @return mixed
     */
    public function index() {
        //查分类
        $categories = Category::all();
        //查出所有的食品
        $products = Product::all();
        $res = [];
        foreach($products as $key=> $product) {
            $res[$product['category_id']][] = $product;
        }
        return $this->fetch('index', compact('categories', 'res'));
    }


    /**
     * 食品详情页
     */

    public function show($id) {
        $product =  Product::where('id', $id)->find();
        $category_process = Config::get('category_process');
        $category_value = Config::get('category_value');
        //判断是属于哪种详情页
        if(in_array($product->category_id, $category_process))
            return view('show_process', ['product'=>$product]);
        elseif(in_array($product->category_id, $category_value))
            return view('show_value', ['product'=>$product]);
        else
            abort(404,'页面找不到');
    }

    /**搜索列表页面
     * @param Request $request
     * @return \think\response\View
     */
    public function foodlist(Request $request) {
        $search = $request->param('name');
        if(isset($search) && trim($search) != '') {
            $map['name'] = ['like', '%'.$search.'%'];
            $lists = Product::where($map)->select();
            return view('list', compact('lists'));
        }
    }

    public function comment() {
        $comments = Comment::with('user')->paginate();
        $page = $comments->render();
        return view('comment', compact('comments', 'page'));
    }


    /**新增评论
     * @param Request $request
     * @return string
     */
    public function storeComment(Request $request) {
        $comment = $request->param('content');
        if($request->has('content') && trim($comment) != '') {
            $result = Comment::create([
                'user_id'=> cookie('uid'),
                'content'=> $comment,
                'createtime'=> time()
            ]);
            if($result) {
                Session::flash('commentError','新增成功~！');
                return  "<script>history.back(-1)</script>";
            }
        }else {
            Session::flash('commentError','请填写留言哟！');
            return "<script>history.back(-1)</script>";
        }
    }

    public function delComment(Request $request) {
        $id = $request->param('id');
        $result = Comment::destroy($id);
        if($result) {
            $this->success('删除成功');
        }else {
            $this->error('删除失败');
        }
    }


}
